package com.bwie.gateway.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhitesConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @className: AuthFilters
 * @Description: TODO
 * @version: v1.８.0
 * @author: 房新路
 * @date: 2025/7/2 17:56
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private IgnoreWhitesConfig ignoreWhitesConfig;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 过滤方法
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断是否是白名单请求
        //获取系统配置好的白名单
        List<String> whites = ignoreWhitesConfig.getWhites();
        //获取当前的请求的URI
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //判断当前的请求的URI 是否是白名单 请求
        if(StringUtils.matches(path,whites)){
            //是白名单 请求 放行
            return chain.filter(exchange);
        }
        //验证token
        //获取token
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        //非空
        if(StringUtils.isBlank(token)){
            return GatewayUtils.errorResponse(exchange,"token不能为空!");
        }
        //对不对 合法性
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange,"token不合法");
        }
        //有效性
        //根据token 获取redis的键
        String userKey = JwtUtils.getUserKey(token);
        if(!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY+userKey)){
            return GatewayUtils.errorResponse(exchange,"token过期");
        }

        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}